'use client';

import { useState, useEffect } from 'react';
import { SqlEditor } from '@/components/SqlEditor';
import { ResultsTable } from '@/components/ResultsTable';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { initDatabase, executeQuery, resetDatabase } from '@/lib/sql-service';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

export default function PlaygroundPage() {
  const [results, setResults] = useState<{ columns: string[]; rows: any[] }>({ columns: [], rows: [] });
  const [error, setError] = useState<string | undefined>();
  const [isLoading, setIsLoading] = useState(true);
  const [schema, setSchema] = useState<{ columns: string[]; rows: any[] }>({ columns: [], rows: [] });

  useEffect(() => {
    const init = async () => {
      try {
        await initDatabase();
        await loadSchema();
        setIsLoading(false);
      } catch (err) {
        console.error('初始化失败:', err);
        setError('数据库初始化失败');
        setIsLoading(false);
      }
    };

    init();
  }, []);

  const loadSchema = async () => {
    try {
      const result = await executeQuery(`
        SELECT 
          name AS 表名,
          sql AS 创建语句
        FROM 
          sqlite_master
        WHERE 
          type='table' AND 
          name NOT LIKE 'sqlite_%'
      `);
      setSchema(result);
    } catch (err: any) {
      console.error('加载数据库结构失败:', err);
    }
  };

  const handleExecute = async (query: string) => {
    setError(undefined);
    try {
      const result = await executeQuery(query);
      setResults(result);

      // 如果是DDL或DML语句，重新加载数据库结构
      if (
        query.trim().toUpperCase().startsWith('CREATE') ||
        query.trim().toUpperCase().startsWith('DROP') ||
        query.trim().toUpperCase().startsWith('ALTER')
      ) {
        await loadSchema();
      }
    } catch (err: any) {
      console.error('查询执行失败:', err);
      setError(err.toString());
      setResults({ columns: [], rows: [] });
    }
  };

  const handleReset = async () => {
    try {
      await resetDatabase();
      setResults({ columns: [], rows: [] });
      setError(undefined);
      await loadSchema();
    } catch (err: any) {
      console.error('重置数据库失败:', err);
      setError(err.toString());
    }
  };

  if (isLoading) {
    return <div className="container mx-auto py-10 px-4 text-center">正在加载SQL环境...</div>;
  }

  return (
    <div className="container mx-auto py-10 px-4">
      <h1 className="text-3xl font-bold mb-6">SQL操作场</h1>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <SqlEditor onExecute={handleExecute} />

          <div className="mt-6">
            <ResultsTable
              columns={results.columns}
              rows={results.rows}
              error={error}
            />
          </div>
        </div>

        <div>
          <Tabs defaultValue="schema">
            <TabsList className="w-full">
              <TabsTrigger value="schema" className="flex-1">数据库结构</TabsTrigger>
              <TabsTrigger value="help" className="flex-1">帮助</TabsTrigger>
            </TabsList>

            <TabsContent value="schema">
              <Card>
                <CardHeader>
                  <CardTitle>数据库表</CardTitle>
                </CardHeader>
                <CardContent>
                  {schema.rows.length > 0 ? (
                    <div className="space-y-4">
                      {schema.rows.map((table, i) => (
                        <div key={i} className="border rounded-md p-3">
                          <h3 className="font-medium">{table['表名']}</h3>
                          <pre className="text-xs mt-2 bg-muted p-2 rounded overflow-x-auto">
                            {table['创建语句']}
                          </pre>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <p>没有表。使用CREATE TABLE语句创建一个表。</p>
                  )}

                  <Button
                    variant="outline"
                    onClick={handleReset}
                    className="mt-4 w-full"
                  >
                    重置数据库
                  </Button>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="help">
              <Card>
                <CardHeader>
                  <CardTitle>SQL帮助</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div>
                      <h3 className="font-medium">创建表</h3>
                      <pre className="text-xs mt-2 bg-muted p-2 rounded">
                        {`CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT UNIQUE
);`}
                      </pre>
                    </div>

                    <div>
                      <h3 className="font-medium">插入数据</h3>
                      <pre className="text-xs mt-2 bg-muted p-2 rounded">
                        {`INSERT INTO users (name, email)
VALUES ('张三', 'zhangsan@example.com');`}
                      </pre>
                    </div>

                    <div>
                      <h3 className="font-medium">查询数据</h3>
                      <pre className="text-xs mt-2 bg-muted p-2 rounded">
                        {`SELECT * FROM users WHERE name LIKE '张%';`}
                      </pre>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>
      </div>
    </div>
  );
} 